package aps

import org.apache.commons.logging.LogFactory
import org.json.JSONObject

/**
 * 重新录入物料校验返回
 * 已存在物料校验
 * 开始作业返回
 * 实时消息
 */
class SHOWMSG2PDAController {

    def topicMsgThreadService
    private final static logger = LogFactory.getLog(this)
    def index() {

        def standardJSONForPDA = JSONObject.newInstance()
        standardJSONForPDA.put("code","200")
        standardJSONForPDA.put("message","")
        standardJSONForPDA.put("data",null)
        def EQPID = params.EQPID

        LinkedList linkList = topicMsgThreadService.newMsgMap?.get(EQPID)
        List alertList = topicMsgThreadService.alertMap?.get(EQPID)

        def result = []
        try {
            def max = topicMsgThreadService.max
            def number = params.number ?: "5"
            number = Integer.parseInt(number)

            if (!alertList) {
                //处理线程安全
                alertList = Collections.synchronizedList(new LinkedList<String>());
                //LinkedList.newInstance()
                topicMsgThreadService.alertMap.put(EQPID, alertList)
            }

            if (linkList) {
                if (number >= max || number > linkList.size()) {
                    result = linkList
                } else {
                    def lastIndex = linkList.size()
                    result = linkList.getAt((lastIndex - number..lastIndex - 1))
                }

                for (JSONObject data : result) {

                    //println "${data.getClass()}值:${data}"
                    def msgId = data?.msgId

                    if (!alertList.contains(msgId)) {
                        alertList.add(msgId)
                    } else {
                        //data.remove("ISALERT")
                        data.put("ISALERT", false)
                    }

                    if (alertList.size() > 5) {
                        alertList.remove(0)
                    }
                }

            }
            standardJSONForPDA.put("data",result)
        }catch (Exception e){
            standardJSONForPDA.put("code","-200")
            standardJSONForPDA.put("message","PDAServer消息处理异常!")


            logger.info("${EQPID} all message:")
            logger.info(linkList)
            logger.info("${EQPID} new message:")
            logger.info(result)
            logger.info("${EQPID} alert message id:")
            logger.info(alertList)

            logger.info("${EQPID} PDAServer message Error！")
            logger.error(e.getMessage())
        }finally{
            render standardJSONForPDA.toString()
        }
    }
}